package com.example.demo.user.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.example.demo.common.Result;
import com.example.demo.user.dto.request.UpdateUserProfileRequest;
import com.example.demo.user.dto.response.UserProfileResponse;
import com.example.demo.user.entity.User;
import com.example.demo.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description 用户信息管理控制器
 * @Author System
 * @Date 2025/9/25
 **/
@RestController
@RequestMapping("/api/user")
@Tag(name = "用户管理", description = "用户信息相关接口")
@SaCheckLogin // 需要登录才能访问
public class UserController {

    private static final Log log = LogFactory.get();
    
    @Autowired
    private UserService userService;

    @GetMapping("/profile")
    @Operation(summary = "获取用户个人信息", description = "获取当前登录用户的详细信息")
    public Result<UserProfileResponse> getUserProfile() {
        try {
            // 获取当前登录用户ID
            Long userId = StpUtil.getLoginIdAsLong();
            log.info("获取用户个人信息，用户ID: {}", userId);
            
            // 从数据库查询用户信息
            User user = userService.getById(userId);
            if (user == null) {
                log.warn("用户不存在，用户ID: {}", userId);
                return Result.fail("用户不存在");
            }
            
            // 构建响应对象
            UserProfileResponse response = UserProfileResponse.builder()
                    .id(user.getId())
                    .username(user.getUsername())
                    .realName(user.getRealName())
                    .email(user.getEmail())
                    .phone(user.getPhone())
                    .department(user.getDepartment())
                    .avatarUrl(user.getAvatarUrl() != null ? user.getAvatarUrl() : "/images/logo.png")
                    .status(user.getStatus())
                    .createTime(user.getCreateTime() != null ? 
                        user.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) : null)
                    .lastLoginTime(user.getLastLoginTime() != null ? 
                        user.getLastLoginTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null)
                    .build();
            
            log.info("获取用户个人信息成功，用户: {}", user.getUsername());
            return Result.success("获取用户信息成功", response);
            
        } catch (Exception e) {
            log.error("获取用户个人信息失败: {}", e.getMessage(), e);
            return Result.fail("获取用户信息失败: " + e.getMessage());
        }
    }

    @PutMapping("/profile")
    @Operation(summary = "更新用户个人信息", description = "更新当前登录用户的个人信息")
    public Result<String> updateUserProfile(@Validated @RequestBody UpdateUserProfileRequest request) {
        try {
            // 获取当前登录用户ID
            Long userId = StpUtil.getLoginIdAsLong();
            log.info("更新用户个人信息，用户ID: {}", userId);
            
            // 查询当前用户
            User user = userService.getById(userId);
            if (user == null) {
                log.warn("用户不存在，用户ID: {}", userId);
                return Result.fail("用户不存在");
            }
            
            // 更新用户信息
            if (request.getRealName() != null) {
                user.setRealName(request.getRealName());
            }
            if (request.getEmail() != null) {
                user.setEmail(request.getEmail());
            }
            if (request.getPhone() != null) {
                user.setPhone(request.getPhone());
            }
            if (request.getDepartment() != null) {
                user.setDepartment(request.getDepartment());
            }
            if (request.getAvatarUrl() != null) {
                user.setAvatarUrl(request.getAvatarUrl());
            }
            
            // 保存到数据库
            boolean success = userService.updateById(user);
            if (success) {
                log.info("用户个人信息更新成功，用户: {}", user.getUsername());
                return Result.success("个人信息更新成功");
            } else {
                log.error("用户个人信息更新失败，用户ID: {}", userId);
                return Result.fail("更新失败");
            }
            
        } catch (Exception e) {
            log.error("更新用户个人信息失败: {}", e.getMessage(), e);
            return Result.fail("更新失败: " + e.getMessage());
        }
    }

    @PostMapping("/avatar")
    @Operation(summary = "上传用户头像", description = "上传并更新用户头像")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 获取当前登录用户ID
            Long userId = StpUtil.getLoginIdAsLong();
            log.info("上传用户头像，用户ID: {}", userId);
            
            if (file == null || file.isEmpty()) {
                return Result.fail("请选择要上传的文件");
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.fail("只支持图片文件");
            }
            
            // 验证文件大小（限制为2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.fail("文件大小不能超过2MB");
            }
            
            // 这里暂时返回默认头像，实际项目中需要实现文件上传逻辑
            String avatarUrl = "/images/logo.png";
            
            // 更新用户头像URL到数据库
            User user = userService.getById(userId);
            if (user != null) {
                user.setAvatarUrl(avatarUrl);
                userService.updateById(user);
            }
            
            Map<String, String> result = new HashMap<>();
            result.put("avatarUrl", avatarUrl);
            
            log.info("用户头像上传成功，用户ID: {}", userId);
            return Result.success("头像上传成功", result);
            
        } catch (Exception e) {
            log.error("上传用户头像失败: {}", e.getMessage(), e);
            return Result.fail("上传失败: " + e.getMessage());
        }
    }
}
